<template>
    <div class="dashboard-container">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">加载中...</div>

        <!-- 错误提示 -->
        <div v-else-if="error" class="error">{{ error }}</div>

        <!-- 正常内容 -->
        <template v-else>
            <el-tabs v-model="activeTab">
                <el-tab-pane v-for="cat in categories" :key="cat.id" :label="cat.categoryName" :name="cat.id" />
            </el-tabs>

            <div class="waterfall-container">
                <div v-for="item in currentData" :key="item.id" class="card-wrapper">
                    <Card :data="{
                        id: item.id,
                        title: item.title,
                        src: item.coverImg,
                        author: item.user.username,
                        avatar: item.user.userPic,
                        likes: item.likes!,
                        comments: item.comments!
                    }" @card-click="handleCardClick" />
                </div>
            </div>
        </template>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCategoryList } from '../../api/category'
import { getArticleList } from '../../api/article'
import { getUserInfo } from '../../api/user'    // 用户信息接口导入
import type { CategoryItem } from '../../types/category'
import type { ArticleItem, ArticleWithUser } from '../../types/article'
import type { MinimalUser } from '../../types/user' // 用户类型导入
import Card from '@/components/Card.vue'

const router = useRouter()

// 新增用户信息缓存
const userCache = new Map<number, MinimalUser>()

// 状态管理（新增用户信息相关状态）
const categories = ref<CategoryItem[]>([])
const articles = ref<ArticleWithUser[]>([])
const activeTab = ref<number>(0)
const loading = ref(true)
const error = ref<string>()

// 生命周期
onMounted(async () => {
    try {
        // 并行请求
        const [catRes, artRes] = await Promise.all([
            getCategoryList(),
            getArticleList()
        ])

        // 处理分类数据
        if (catRes.data.code === 1) {
            categories.value = catRes.data.data
            if (categories.value.length > 0) {
                activeTab.value = categories.value[0].id
            }
        }

        // 处理文章数据
        // 有问题，getUserInfo接口请求次数太多
        if (artRes.data.code === 1) {
            articles.value = await Promise.all(
                artRes.data.data.map(async (item: ArticleItem) => {
                    try {
                        let userInfo = userCache.get(item.createUser)
                        if (!userInfo) {
                            const res = await getUserInfo(item.createUser.toString())
                            if (res.data.code === 1) {
                                userInfo = {
                                    id: res.data.data.id,
                                    username: res.data.data.username,
                                    userPic: res.data.data.userPic
                                        ? res.data.data.userPic
                                        : `https://i.pravatar.cc/40?u=${item.createUser}`
                                }
                                userCache.set(item.createUser, userInfo) 
                            }
                        }

                        return {
                            ...item,
                            likes: item.likes || 0,
                            comments: item.comments || 0,
                            user: userInfo || {
                                id: item.createUser,
                                username: `用户${item.createUser}`,
                                avatar: `https://i.pravatar.cc/40?u=${item.createUser}`
                            }
                        } as ArticleWithUser
                    } catch (error) {
                        console.error('用户信息获取失败:', error)
                        return {
                            ...item,
                            likes: item.likes || 0,
                            comments: item.comments || 0,
                            user: {
                                id: item.createUser,
                                username: `用户${item.createUser}`,
                                avatar: `https://i.pravatar.cc/40?u=${item.createUser}`
                            }
                        } as ArticleWithUser
                    }
                })
            )
        }
    } catch (err) {
        error.value = (err as Error).message || '数据加载失败'
    } finally {
        loading.value = false
    }
})

// 当前分类文章
const currentData = computed(() => {
    return articles.value.filter(
        item => item.categoryId === activeTab.value
    ) as ArticleWithUser[]
})

// 点击Card组件的事件处理
const handleCardClick = (id: number) => {
    router.push({
        name: 'article',
        params: { id }
    })
}

</script>

<style lang="less" scoped>
.dashboard-container {
    // 适配index.vue的主内容区域
    padding: 0 24px;
    margin-top: 72px;
    /* 为顶部栏留出空间 */

    // 修复Tabs定位问题
    .tabs-wrapper {
        position: sticky;
        top: 72px;
        /* 位于顶部栏下方 */
        z-index: 9;
        /* 低于顶部栏的z-index */
        background: #fff;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        margin-bottom: 24px;

        // 同步index.vue的侧边栏宽度
        @media screen and (min-width: 1728px) {
            margin-left: 266.66667px;
        }
    }

    // Tabs文字颜色修复
    :deep(.custom-tabs) {
        .el-tabs__header {
            margin: 0;
            padding: 0 24px;

            .el-tabs__nav-wrap::after {
                background-color: transparent !important;
            }

            .el-tabs__item {
                font-size: 15px;
                color: #666 !important;
                padding: 0 24px !important;
                height: 56px;

                &.is-active {
                    color: #eb4d4b !important;
                }

                &:hover {
                    color: #eb4d4b !important;
                }
            }

            .el-tabs__active-bar {
                background-color: #eb4d4b;
            }
        }
    }

    // 瀑布流布局适配
    .waterfall-container {
        column-count: 4;
        column-gap: 24px;
        margin-top: 0;
        /* 移除多余间距 */

        // 响应式调整
        @media (max-width: 1440px) {
            column-count: 3;
        }

        @media (max-width: 1024px) {
            column-count: 2;
        }

        @media (max-width: 768px) {
            column-count: 1;
        }
    }

    // 适配index.vue的侧边栏布局
    @media screen and (min-width: 1728px) {
        margin-left: 266.66667px;
        width: calc(100% - 266.66667px);
    }
}
</style>
